package org.example.memora.service.serviceImpl;

import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.N;
import org.example.memora.common.enumeration.ApplicationStatus;
import org.example.memora.common.utils.UserHolder;
import org.example.memora.entity.CommunityJoinApplication;
import org.example.memora.entity.CommunityUser;
import org.example.memora.entity.NotifyMessage;
import org.example.memora.mapper.CommunityJoinApplicationMapper;
import org.example.memora.mapper.CommunityUserMapper;
import org.example.memora.service.CommunityJoinApplicationService;
import org.example.memora.service.CommunityService;
import org.example.memora.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CommunityJoinApplicationServiceImpl implements CommunityJoinApplicationService {

    private final CommunityJoinApplicationMapper applicationMapper;
    private final CommunityUserMapper communityUserMapper;
    @Autowired
    private final CommunityService communityService;
    private final NotificationService notificationService;

    @Override
    public boolean applyToJoinCommunity(Long communityId, Long userId, String reason) {
        // 查询是否已有申请
        CommunityJoinApplication existing = applicationMapper.selectByCommunityIdAndUserId(communityId, userId);
        if (existing != null && existing.getStatus() == ApplicationStatus.PENDING) {
            // 已申请且还未审核
            return false;
        }

        CommunityJoinApplication application = new CommunityJoinApplication();
        application.setCommunityId(communityId);
        application.setUserId(userId);
        application.setReason(reason);
        application.setStatus(ApplicationStatus.PENDING);
        application.setCreatedAt(LocalDateTime.now());
        application.setUpdatedAt(LocalDateTime.now());
        CommunityUser user = communityUserMapper.selectByCommunityIdAndUserId(communityId, userId);
        if(user!=null){
            return false;
        }
        boolean success=applicationMapper.insert(application) > 0;
        if (success) {
            // 找出群主
            Long ownerId = communityService.getOwnerIdByCommunityId(communityId);
            NotifyMessage notify = new NotifyMessage();
            notify.setType("JOIN_REQUEST");
            notify.setFromUserId(userId);
            notify.setToUserId(ownerId);
            notify.setCommunityId(communityId);
            notify.setContent("用户 " + userId + " 申请加入群 " + communityId);
            notificationService.sendToUser(ownerId, notify);
        }
        return success;
    }

    @Override
    public List<CommunityJoinApplication> getPendingApplications(Long communityId) {
        return applicationMapper.selectPendingByCommunityId(communityId);
    }

    @Override
    public boolean reviewApplication(Long applicationId, String status) {
        // 更新申请状态
        boolean updated = applicationMapper.updateStatus(applicationId, status) > 0;
        if (!updated || !"APPROVED".equals(status)) {
            return updated;
        }

        // 查询申请信息
        CommunityJoinApplication application = applicationMapper.selectById(applicationId);
        if (application == null) return false;

        // 添加到社群成员表
        CommunityUser user = new CommunityUser();
        user.setCommunityId(application.getCommunityId());
        user.setUserId(application.getUserId());
        user.setRole("member");
        user.setJoinedAt(Instant.now());
        if (updated) {
            Long applicantId = applicationMapper.selectUserIdById(applicationId);
            // 你需要写这个方法
            Long communityId = applicationMapper.selectCommunityIdById(applicationId);

            NotifyMessage notify = new NotifyMessage();
            notify.setType("REVIEW_RESULT");
            notify.setFromUserId(UserHolder.getUser().getUserId());
            // 群主
            notify.setToUserId(applicantId);
            notify.setCommunityId(communityId);
            notify.setContent("你加入群 " + communityId + " 的申请已被" + ("APPROVED".equals(status) ? "通过" : "拒绝"));

            notificationService.sendToUser(applicantId, notify);
        }
        return  communityUserMapper.insert(user)>0;
    }
}

